import { onBeforeUnmount, onMounted, ref } from "vue";
import { debounce } from "@/common/tools";

// 默认适配宽高
export const width = 1920;
export const height = 1080;

type ResizeType = {
  w?: number;
  h?: number;
  fullScreen?: boolean;
  delay?: number;
};

export const useResize = (options: ResizeType = {}) => {
  const { w = width, h = height, fullScreen = false, delay = 100 } = options;
  const screenRef = ref();
  const scale = ref(1);

  function resize() {
    //获取浏览器宽度
    const clientWidth = document.body.clientWidth;
    //获取浏览器高度
    const clientHeight = document.body.clientHeight;
    //计算缩放比例
    const scaleW = clientWidth / w;
    const scaleH = clientHeight / h;
    scale.value = Math.min(scaleW, scaleH);

    if (fullScreen) {
      // 全屏 宽高比可能不协调
      screenRef.value.style.transform = `scale(${scaleW}, ${scaleH})`;
    } else {
      // 根据宽高比 进行缩放
      screenRef.value.style.transform = `scale(${scale.value})`;
      // 设置居中
      screenRef.value.style.left = `${(clientWidth - w * scale.value) / 2}px`;
      screenRef.value.style.top = `${(clientHeight - h * scale.value) / 2}px`;
      // screenRef.value.style.position = "absolute";
    }
  }

  const resizeDelay = debounce(resize, delay);
  onMounted(() => {
    if (screenRef.value) {
      resize();
      // 监听窗口变化
      window.addEventListener("resize", resizeDelay);
    }
  });

  onBeforeUnmount(() => {
    window.removeEventListener("resize", resizeDelay);
  });

  return {
    screenRef,
    scale,
  };
};
